import $ from 'jquery';
var APPID = 'wx12e47c51b1faece1';


export default {
	openid: '',
	code: '',
	access_token: '',

	startAuth: function(callback) {
		// 第一次：http://meyley.com
        // 第二次：http://meyley.com/?code=xxxx&state=STATE
        // 微信授权

        var code = this.getQueryString('code');
        // 第一步 用户同意授权，获取code
        if(!code) {
            location.href = this.getAuthUrl()
            return false;
        }

        this.code = code;
        this.getAccessCode(callback)
	},
    getAuthUrl() {
        var url = window.location.href;
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri='+ encodeURIComponent(url) +'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
    },
	// 第二步：通过code换取网页授权access_token
    getAccessCode: function(callback) {
        var ctx = this;

        $.ajax({
            url: 'http://www.meyley.cn/getAccess/' + APPID + '/' + this.code,
            success: function(data) {
                ctx.access_token = data.access_token;
                ctx.openid = data.openid;
                callback && callback(data)
                // ctx.getUserInfo()
            }
        })
    },
    // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
    // getUserInfo: function() {
    //     var ctx = this;

    //     $.ajax({
    //         url: '/getUserInfo/' + this.access_token + '/' + this.openid,
    //         success: function(data) {
    //             ctx.openid = data.openid;
    //             ctx.nickname = data.nickname;
    //         }
    //     })
    // },


	getQueryString: function(name) { 
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); 
        var r = window.location.search.substr(1).match(reg); 
        if (r!=null) return unescape(r[2]); return null; 
    }  
}